package com.bjpowernode.mq;

import cn.hutool.json.JSONUtil;
import com.bjpowernode.mq.models.UserForm;
import jakarta.annotation.Resource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class MqApplication implements CommandLineRunner {

	private static final String MQ_TASK="GATEWAY:NOTIFY:ORIGIN";
	private static final String MQ_TASK_BACK="GATEWAY:NOTIFY:BACK";

	@Resource
	private StringRedisTemplate stringRedisTemplate;

	public static void main(String[] args) {
		SpringApplication.run(MqApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		//生产者,产生数据到Redis
		ListOperations<String,String> listOps = stringRedisTemplate.opsForList();
		//向list中添加成员
		UserForm userForm = new UserForm("24", "3","245", "35", "ok", "SUCCESS", "WINXIN","fdfffd");
		Thread threadSupplier = new Thread(() -> {

			try {
				String task = JSONUtil.toJsonStr(userForm);
				for(int i =0;i <10;i++){
					System.out.println("生产者,生成的消息="+task);
					listOps.leftPush(MQ_TASK,task);
					TimeUnit.SECONDS.sleep(3);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		threadSupplier.start();
		//消费者,从List读取数据
		Thread threadConsumer = new Thread(()->{
			try {
				while (true) {
					String task = listOps.rightPopAndLeftPush(MQ_TASK,MQ_TASK_BACK,300,TimeUnit.MILLISECONDS);
					if(task==null){
						throw new InterruptedException("读取数据完成");
					}
					System.out.println("消费者读取的task="+task);
				}

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		//threadConsumer.start();
	}
}

